package com.biubiux2.client;

import com.biubiux2.security.KeyNegotiationContext;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author Lijinbao
 * @since 8/5/2022 4:51 PM
 */
public class Client {

    public static Channel run(String host, int port, SimpleChannelInboundHandler<ByteBuf> messageReceivedHandler) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            ClientChannelInitializer initializer = new ClientChannelInitializer();
            initializer.addExtraChannelHandler(messageReceivedHandler);

            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(initializer);
            Channel channel = b.connect(host, port).sync().channel();
            channel.closeFuture().addListener((ChannelFutureListener) future -> group.shutdownGracefully());

            return channel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
